
export const arr2str = (arr: ByteBuffer): string => new TextDecoder().decode(arr);

export function err(message: string, code?: string): never {
    const e = new Error(message)
    if (code)
        (e as any).code = code
    throw e
}

export const errNotImpl = (): never => err("not implemented");

export const throwENOTDIR = (absolutePath: string) => err(`ENOTDIR: not a directory, scandir '${absolutePath}'`, "ENOTDIR");

export const throwENOENT = (absolutePath: string) => err(`ENOENT: no such file or directory, scandir '${absolutePath}'`, 'ENOENT')

function writeBack(absolutePath: string, content: ByteBuffer | null | undefined) {
  postMessage({ f: 'WRITE', x: { path: absolutePath, content } })
}

export const isDirIndicator = (absolutePath: string) => `<title>Index of ${absolutePath}`;

export const isDir = (absolutePath: string, buffer: ByteBuffer | undefined): boolean => !!buffer && arr2str(buffer).includes(isDirIndicator(absolutePath));

export function rawReadHttpServer(absolutePath: string): ByteBuffer | undefined {
  const request = new XMLHttpRequest()
  request.responseType = 'arraybuffer'
  request.open('GET', absolutePath, false)
  request.send(null)
  if (request.status === 200) {
    writeBack(absolutePath, request.response)
    return new Uint8Array(request.response)
  }
  return undefined
}